<?php
/**
 * 子应用入口
 * @param  array
 * @return [type]
 */
function run_category_app($uri = array()) {
	$request_uri = str_replace('/index.php', '', $_SERVER['REQUEST_URI']);
	if (!empty($request_uri)) {
		//显示下级分类
		$rule = "/index_(.*)\\.html/i";
		preg_match($rule, $request_uri, $results);
		$page = 1;
		//判断是否包含页码
		if (isset($results[1])) {
			$page = intval($results[1]);
		}
		category_show_page($request_uri, $page);
	} else {
		//显示分类首页
		$parameter = "category";
		$page = 1;
		category_show_page($parameter, $page);
	}
}

/**
 *显示category页面
 */
function category_show_page($category_path = '', $page = 1) {
	$page = intval($page);
	$category_path = trim($category_path);
	$last = substr($category_path, -1);
	$category_index_file = $category_path . '/index.html';
	if ($last == '/') {
		$category_path = substr($category_path, 0, -1);
	}
	//如果是大于1页的，则处理页码
	if ($page > 1) {
		$category_index_file = $category_path . '/index_' . $page . '.html';
	}
	// app start.
	if (is_file($category_index_file) && (time() - filemtime($category_index_file) < 1200) && !IS_DEBUG) {
		//缓存未失效则直接加载静态文件
		require_once $category_index_file;
	} else {
		require_once APP_PATH . DIRECTORY_SEPARATOR . 'category/model.php';
		$category_data = false;
		if ($category_path == '/category') {
			//如果是分类首页
			$category_data = array();
			$category_data['id'] = 0;

		} else {
			//获取数据
			$category_data = category_model_get_by_category_path($category_path);

		}
		//输出
		if ($category_data) {
			$category_data = get_site_data($category_data);
			//文件保存路径
			$html_file_dir = ROOT_PATH . $category_path;
			$html_file_path = ROOT_PATH . $category_index_file;
			//写入文件
			if (!file_exists($html_file_dir)) {
				mkdir($html_file_dir, 0777, true);
			}

			require_once APP_PATH . DIRECTORY_SEPARATOR . 'post/model.php';

			$category_data['post_list'] = post_model_get_list_by_category_id($category_data['id'], $page);

			require_once APP_PATH . DIRECTORY_SEPARATOR . 'category/build.php';
			$html = category_build_html($category_data);
			echo $html;
		} else {
			show_not_found();
		}
	}
}